package com.syl.filter;

import com.google.gson.Gson;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname UserFilter
 * @Description 对admin操作进行权限控制
 * @Date 2025/8/4 19:18
 * @Created by SYL
 */

@WebFilter("/user/delect")
public class UserFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {


        System.out.println("UserFilter");
        //获取请求接口
              HttpServletRequest rep=(HttpServletRequest)servletRequest;
              //获取session
        HttpSession session = rep.getSession(false);
        if (session!=null&&session.getAttribute("user")!=null){  //验证  session有没有登录
            System.out.println("session = " + session.getAttribute("user"));
            filterChain.doFilter(servletRequest,servletResponse);  //通过
        }else {
            //不通过返回json数据
            // 构造符合前端期望的响应格式
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("msg",false );
            System.out.println("result = " + result);

            // 使用 Gson 将对象转换为 JSON 字符串
            Gson gson = new Gson();
            String json = gson.toJson(result);
            System.out.println("json = " + json);

            // 写入响应
            HttpServletResponse resp=(HttpServletResponse)servletResponse;
            resp.getWriter().write(json);
        }
    }

    @Override
    public void destroy() {

    }
}
